package servlets;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class RegisterPatientServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String gender = request.getParameter("gender");
		String dateOfBirth = request.getParameter("dateOfBirth");
		String address = request.getParameter("address");
		String occupation = request.getParameter("occupation");
		String physician = request.getParameter("physician");
		Integer status = Integer.parseInt(""
				+ request.getParameter("clinicalStatus"));
		String medicalHistory = request.getParameter("medicalHistory");

		Patient patient = null;
		try {
			patient = PatientManager.getInstance().createPatient(name, gender,
					occupation, address, status, physician,
					DateFormatter.getDateformatter().parse(dateOfBirth + " 00:00:00"),
					new Date(), medicalHistory);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Map<String, Object> data = new HashMap<String, Object>();

		if (patient != null) {
			data.put("id", patient.getPatientId());
			data.put("name", patient.getName());
			data.put("physician", patient.getPhysician());
			data.put("gender", patient.getGender());
		}

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(data));
	}

}
